import {getGoodsCatelog,getMianData,getSubCatelog,getGoodsSecondListXCX} from '../../../Tools/HTTPOpertion.js';
Page({
  data: {
    color1:'#F49F11',
    color2:'#999999',
    class1:'zheng',
    class2:'',
    page: 1,
    julIf: false,
    popupIf: false,
    index: -1,
    windowHeight: 1200,
    Popup_inde: 0,
    Popup_inde2: 0,
    Popup_inde3: 0,
    PopupIf: false,
    unionidPopupIf: false,
    name: '',
    windowHeight: '',
    list: [],
    className: "",
    scrollHeight: 0,
    positionType: "nor",
    subList: [],
    typeList: [],
    Popup_index_right: 0,
    types: "全部分类",
    orderType: "排序",
    peisongType: "配送方式",
    superID: 0,
    goods: [],
    a1: '',//分类id
    a2: '',
    a3: '',
    a4:'1',//秒杀类别
    a5:'',//搜索
    imgURL: '',
    topPic: {},
    hasMore: true,
    countDown:[],
    countDown1: [],
    startJZ:false,
    name1: '', //筛选蒙层
    bull: true, //页面滚动
    top1: 0,
    tabScrollTop: 0,
    interval:[]  //daojishi
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 调取全部分类的接口
    this.getGoodsCatelog();
    this.loadMainData();
    this.loadData(1);
  },
  onShow: function () {

  },
  // 获取 全部分类 中数据
  getGoodsCatelog: function () {
    const that = this;
    getGoodsCatelog({}).then(function (result) {
      console.log('getGoodsCatelog result', result);
      var temp = [{ name: "全部", id: 0 }].concat(result.data);
      that.setData({
        typeList: temp,
      });

    }).catch(function (error) {

    });

  },
  // 加载全部分类二级数据
  loadMainData: function () {
    wx.showLoading({
      title: '加载中'
    })
    var self = this;
    var config = { intPara2: wx.getStorageSync("level"), cnd: wx.getStorageSync("city"), latitude: wx.getStorageSync("latitude"), longitude: wx.getStorageSync("longitude") };
    console.log(config);
    getMianData(config).then(function (result) {
      console.log(result);
      var temp = [{ name: "全部", id: 0 }].concat(result.data.catalogList);

      let topPics = result.data.topPics;
      topPics = topPics && topPics.filter(item => item.activity_type == 3);
      const topPic = topPics && topPics[0];
      const imgURL = topPics && topPics[0] && topPics[0].img_url;
      self.setData({
        subList: [{ name: "不限", id: null }],
        obj: result.data,
        list: result.data.merchantList,
        // typeList: temp,
        topPic,
        imgURL,
      });
      // self.data.typeList.unshift({name:"全部",id:0});
      // console.log(self.data.typeList);
      wx.hideLoading();
      wx.stopPullDownRefresh();
    }).catch(function (error) {
      console.log(error);
      wx.hideLoading();
      wx.stopPullDownRefresh()
    });
  },

  // banner点击跳转对应页面
  bannerLink: function () {
    const topPic = this.data.topPic;
    const id = topPic.activity_id;
    id && wx.navigateTo({
      url: 'pages/active/miaoshaDetails/miaoshaDetails?id={{id}}&times=123',
    })
  },
  // 具体列表跳转地址
  toGroupDetail: function (e) {
    console.log(e)
    const id = e.currentTarget.dataset.id;
    const miaoTime = e.currentTarget.dataset.miaotime;
    const merchantName = e.currentTarget.dataset.merchantname;
    const startdate = e.currentTarget.dataset.startdate;
    const enddate = e.currentTarget.dataset.enddate;
    wx.navigateTo({
      url: "/pages/active/miaoshaDetails/miaoshaDetails?id=" + id + "&miaoTime=" + miaoTime + "&merchantName=" + merchantName + "&startdate=" + startdate + "&enddate=" + enddate +'&times=12',
    })
  },
  // 超出加载中
  PopupF: function () {
    console.log("....");
    this.setData({
      PopupIf: false,
      unionidPopupIf: false,
      peisongPopupIf: false,
    })
  },
  //分类列表筛选点击
  PopupBoxLeftChoose: function (e) {
    var self = this;
    var id = typeof e == "number" ? 10 : e.currentTarget.dataset.id;
    console.log('id:', id);
    if (id == 0) {
      self.setData({
        subList: [],
        Popup_inde: 0,
        types: "全部",
        superID: e.currentTarget ? e.currentTarget.dataset.id : 0,
        a1: '',
        a2: '',
        a3: '',
      });
      this.loadData(1);
      this.returnType();
      return;
    }
    self.setData({
      superID: e.currentTarget.dataset.id,
      Popup_index_right: 0
    });

    getSubCatelog({ intPara2: wx.getStorageSync("city"), level: wx.getStorageSync("level"), latitude: wx.getStorageSync("latitude"), longitude: wx.getStorageSync("longitude"), intPara: self.data.superID }).then(function (result) {
      var temp = [{ name: "不限", id: 0 }].concat(result.data.list);
      console.log(result);
      self.setData({
        subList: temp,
        Popup_inde: e.currentTarget.dataset.index,
        types: e.currentTarget.dataset.name,
      });
      wx.hideLoading()
    }).catch(function (error) {
      wx.hideLoading()
    });
  },
  //貌似无用哦
  navListTap: function (e) {
    var name = e.currentTarget.dataset.name;
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '',
    })
    this.returnType();
  },
  // 貌似无用
  scrolling: function (e) {
    if (this.data.positionType === "nor") {
      if (e.detail.scrollTop > (47 + 52)) {
        this.setData({
          positionType: "fixed",
          PopupIf: false,
          unionidPopupIf: false,
          peisongPopupIf: false,
          paddingTop: 92 + 15
        });
      }
    } else {
      if (e.detail.scrollTop < (47 + 52)) {
        this.setData({
          positionType: "nor",
          PopupIf: false,
          unionidPopupIf: false,
          peisongPopupIf: false,
          paddingTop: 0
        });
      }
    }

  },
  // 无用
  returnType: function () {
    this.setData({
      unionidPopupIf: false,
      peisongPopupIf: false,
      PopupIf: false
    })
  },
  //弹窗-左侧-筛选
  shTap: function (e) {
    console.log(e)
    this.setData({
      unionidPopupIf: false,
      peisongPopupIf: false,
      PopupIf: !this.data.PopupIf,
      name1: 'cont',
      bull: false,
      top1: this.data.tabScrollTop
    })
    if (this.data.positionType === "fixed") {
      this.setData({
        top: "top"
      })
    }
    if (this.data.unionidPopupIf == false && this.data.peisongPopupIf == false && this.data.PopupIf == false) {
      this.setData({
        name1: '',
        bull: true,
        top1: this.data.tabScrollTop
      })
    }
  },
  //弹窗-右侧-筛选
  unionidTap: function () {
    this.setData({
      PopupIf: false,
      unionidPopupIf: !this.data.unionidPopupIf,
      peisongPopupIf: false,
      name1: 'cont',
      bull: false,
      top1: this.data.tabScrollTop
    })
    if (this.data.unionidPopupIf == false && this.data.peisongPopupIf == false && this.data.PopupIf == false) {
      this.setData({
        name1: '',
        bull: true,
        top1: this.data.tabScrollTop
      })
    }
  },
  // 最右侧筛选
  peisongTap() {
    this.setData({
      PopupIf: false,
      unionidPopupIf: false,
      peisongPopupIf: !this.data.peisongPopupIf,
      name1: 'cont',
      bull: false,
      top1: this.data.tabScrollTop
    })
    if (this.data.unionidPopupIf == false && this.data.peisongPopupIf == false && this.data.PopupIf == false) {
      this.setData({
        name1: '',
        bull: true,
        top1: this.data.tabScrollTop
      })
    }
  },
  //筛选点击**
  PopupBoxLeft: function (e) {
    wx.showLoading({
      title: '加载中',
    })
    var self = this;
    var id = e.currentTarget.dataset.id;
    console.log(e);
    if (id == 0) {
      self.setData({
        Popup_index_right: 0,
        orderType: "全部",
      });
    } else {
      this.setData({
        Popup_index_right: e.currentTarget.dataset.index,
        types: e.currentTarget.dataset.name
      })
    }
    console.log(id);
    this.data.a1 = id;
    this.loadData(1, true).then(function () {
      self.setData({
        PopupIf: !self.data.PopupIf,
        peisongPopupIf: false,
        unionidPopupIf: false
      });
    });
    this.setData({ PopupIf: false })
  },
  //右侧-筛选**
  PopupBoxRight: function (e) {

    wx.showLoading({
      title: '加载中',
    })
    console.log(this.data.PopupIf);
    this.setData({
      Popup_inde2: e.currentTarget.dataset.index,
      orderType: e.currentTarget.dataset.name
    })
    var self = this;
    this.data.a2 = e.currentTarget.dataset.id
    this.loadData(1, true).then(function () {
      self.setData({
        PopupIf: false,
        peisongPopupIf: false,
        unionidPopupIf: !self.data.unionidPopupIf
      });
    });
    this.unionidTap()

  },

  PopupBoxPeisong: function (e) {
    console.log(e)
    wx.showLoading({
      title: '加载中',
    })
    this.setData({
      Popup_inde3: e.currentTarget.dataset.index,
      peisongType: e.currentTarget.dataset.name
    })
    var self = this;
    this.data.a3 = e.currentTarget.dataset.id
    this.loadData(1, true).then(function () {
      self.setData({
        PopupIf: false,
        unionidPopupIf: false,
        peisongPopupIf: !self.data.peisongPopupIf,
      });
    });
    // this.unionidTap()
    this.setData({
      PopupIf: false,
      unionidPopupIf: false,
      peisongPopupIf: !self.data.peisongPopupIf,
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.loadData(1);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log("onReachBottom");
    this.setData({
      page: ++this.data.page
    })
    this.loadList(this.data.page);
  },
  //
  yhTap: function (e) {
    var name = e.currentTarget.dataset.name;
    wx.navigateTo({
      url: '/pages/others/purchaseCoupon/purchaseCoupon'
    })
    this.returnType();
  },
  //
  tsTap: function (e) {
    var name = e.currentTarget.dataset.name;
    wx.navigateTo({
      url: '/pages/others/exploreExperience/exploreExperience'
    })
    this.returnType();
  },
  /**
   * intPara 分类
   * intPara2 排序规则 1 返金由高到低 2 人气由高到低 3价格由高到低
   */
  loadData: function (page, sf) {
    this.setData({
      name1: '',
      bull: true,
    })
    var intPara = this.data.a1;
    var intPara2 = this.data.a2;
    var intPara3 = this.data.a4;
    var intPara4 = this.data.a3;
    var intPara5=this.data.a5;
    var self = this;
    const citybox = wx.getStorageSync('citybox');

    console.log(citybox)
    const codeid = citybox;
    return new Promise(function (success, fail) {
      var config = {
        page: page,
        rows: 10,
        token: wx.getStorageSync('token'),
        areaId: codeid,
        latitude: wx.getStorageSync("latitude"),
        longitude: wx.getStorageSync("longitude")
      };
      if (intPara) { config.intPara = intPara }
      if (intPara2) {
        config.intPara2 = intPara2
        if (intPara2 == 4) {
          config.latitude = wx.getStorageSync('latitude');
          config.longitude = wx.getStorageSync('longitude');
        }
      }
      if (intPara3) { config.intPara3 = intPara3 }
      if (intPara5) { config.intPara5 = intPara5 }
      if (intPara4) { config.intPara4 = intPara4 }
      // 秒杀
      getGoodsSecondListXCX(config).then(function (res) {
        if (res.code === 0) {
          if (page === 1) {
            var listData = res.data.list
            self.setData({
              goods: listData,
              hasMore: listData.length >= 10 ? true : false,
              startJZ:true
            });
          } else {
            const goods = self.data.goods
            var listData = goods.concat(res.data.list);
            self.setData({
              goods: listData,
              hasMore: res.data.list.length >= 10 ? true : false
            });
          }
          if (self.data.a4 == 1) {
              self.theTime(self.data.goods)
          }else if (self.data.a4 == 2) {
              self.theTime1(self.data.goods)
          }


          if (res.data.list.length == 0) {
            wx.showToast({
                title: '没有更多数据',
                icon: 'success',
                duration: 2000
            })
          }
        } else {
          wx.showToast({
            title: res.message,
            duration: 2000
          })
        }
      }).catch(function (err) {
        wx.hideLoading();
      });
    });
  },

  //上滑加载
  shjiaz: function () {
    if (this.data.hasMore) {
      this.data.page += 1
      this.loadData(this.data.page);
    } else {
      wx.showToast({
        title: '没有更多数据',
        icon: 'none',
        duration: 2000
      })
    }
  },
  //弹窗
  popupTap: function (e) {
    var that = this;
    var ind = e.currentTarget.dataset.ind;
    var index = that.data.index;
    if (index == ind) {
      that.setData({
        popupIf: !that.data.popupIf,
        index: ind
      })
    } else {
      that.setData({
        popupIf: true,
        index: ind
      })
    }
  },
  zhengmiao:function(e){
    this.setData({
      class1:'zheng',
      class2:'',
      a4: e.currentTarget.dataset.miao,
      countDown: [],
      countDown1: []
    })

    console.log(e)
    this.loadData(1);
  },
  jiangmiao: function (e) {
    this.setData({
      class2: 'zheng',
      class1: '',
      a4: e.currentTarget.dataset.miao,
      countDown: [],
      countDown1: []
    })

    console.log(e)
    this.loadData(1);
  },
  // 倒计时(正在秒杀)
  theTime: function (arr) {
    var that=this;
    that.setData({
      interval:[]
    })

    var totalSecond = [];
    for (var i = 0; i < arr.length; i++) {
          totalSecond.push(arr[i].end_date - Date.parse(new Date()) / 1000);
    }
    var hr = [], hrStr = [], min = [], minStr = [], sec = [], secStr=[],index='',neirong=[];
    for (var i = 0; i < totalSecond.length;i++){
        (function(i){
          if (totalSecond[i] < 0) {
            console.log('活动已结束')
            this.setData({
              countDown: "00:00:00",
              miaoTime: 3
            });
          }
        // 小时位
        hr[i]= Math.floor(totalSecond[i] / 3600);
        hrStr[i] = hr[i]+'';
        if (hrStr[i].length == 1) hrStr[i] = '0' + hrStr[i];
        // 分钟位
        min[i] = Math.floor((totalSecond[i] - hr[i] * 3600)/ 60);
        minStr[i] = min[i]+'';
        if (minStr[i].length == 1) minStr[i] = '0' + minStr[i];

        neirong[i] = hrStr[i] + '时' + minStr[i]+'分';
         // 倒计时设置
         that.setData({
           countDown: neirong
        })
      })(i)
    }

},
  // 倒计时(即将开始)
  theTime1: function (arr) {
    // clearInterval(interval);
        var that= this;
        // that.data.interval = [];
        that.setData({
          interval: []
        })
        var totalSecond = [];
        for(var i = 0; i<arr.length; i++) {
             totalSecond.push(arr[i].start_date - Date.parse(new Date()) / 1000);
      }
      console.log(totalSecond)
      var  hr = [], hrStr = [], min = [], minStr = [], sec = [], secStr = [], index = '', neirong = [];
      for (var i = 0; i < totalSecond.length; i++) {
        (function (i) {
          if (totalSecond[i] < 0) {
            console.log('活动已开始')
            this.setData({
              countDown1: "00:00:00",
              miaoTime: 1
            });
          }
            // 小时位
            hr[i] = Math.floor(totalSecond[i] / 3600);
            hrStr[i] = hr[i] + '';
            if (hrStr[i].length == 1) hrStr[i] = '0' + hrStr[i];
            // 分钟位
            min[i] = Math.floor((totalSecond[i] - hr[i] * 3600) / 60);
            minStr[i] = min[i] + '';
            if (minStr[i].length == 1) minStr[i] = '0' + minStr[i];
            neirong[i] = hrStr[i] + '时' + minStr[i]+'分';
            // 倒计时设置
            that.setData({
              countDown1: neirong
            })
        })(i)
      }
  },
  markTap: function () {
    console.log('左')
    this.setData({
      name1: '',
      bull: true,
      PopupIf: false,
      unionidPopupIf: false,
      peisongPopupIf: false,
    })
  }

})
